package com.gibs.peixunapi.handle;

import com.gibs.peixunapi.enums.ResultEnum;
import com.gibs.peixunapi.excepiton.BaseException;
import com.gibs.peixunapi.result.Result;
import com.gibs.peixunapi.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.persistence.EntityNotFoundException;
import javax.servlet.http.HttpServletRequest;
import java.util.logging.LogManager;

/**
 * @author liangjiawei
 * @date 2020/08/20/11:18
 * @Version 1.0
 * @Description:
 */


@ControllerAdvice
@Slf4j
public class GlobalExceptionHandle {

    /**
     * 处理自定义的业务异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = BaseException.class)
    @ResponseBody
    public Result baseExceptionHandler(HttpServletRequest req, BaseException e){
        log.error("发生业务异常！原因是：{}",e.getMessage());
        return ResultUtil.error(e.getCode(),e.getMessage());
    }

    @ExceptionHandler(value = EntityNotFoundException.class)
    @ResponseBody
    public Result entityNotFoundException(HttpServletRequest request, EntityNotFoundException e) {
            log.info("发生业务异常！原因是：{}",e.getMessage());
            return ResultUtil.error(ResultEnum.DATA_NOT_FIND);
    }

    @ResponseBody
    @ExceptionHandler(NullPointerException.class)
    public Result errorHandler(NullPointerException ex) {
        log.error("发生空指针异常！原因是:",ex);
        return ResultUtil.error(ResultEnum.UNKONW_ERROR);
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result handleException(HttpServletRequest request, Exception e) {
        if (e instanceof BaseException) {
            baseExceptionHandler(request, (BaseException) e);
        } else if (e instanceof EntityNotFoundException) {
            entityNotFoundException(request, (EntityNotFoundException) e);
        }else{
            log.error("未知异常！原因是:{}",e.getMessage());
            return ResultUtil.error(ResultEnum.SERVER_ERROR);
        }
        return null;
    }
}
